﻿using System;
using System.Collections.Generic;

using System.IO;

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using WpfCanvas.Contour;

namespace WpfCanvas
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.cWidth = this.canDrawing.ActualWidth;
            this.cHeight = this.canDrawing.ActualHeight;
            this.SizeChanged += new System.Windows.SizeChangedEventHandler(MainWindow_Resize);
        }

        public static string[] colors = { "006837", "1a9850", "66bd63", "a6d96a", "d9ef8b", "ffffbf", "fee08b", "fdae61", "f46d43", "d73027", "a50026" };

        private ReadInTemp ReadInData { get; set; }

        private double cWidth;
        private double cHeight;

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == true) {
                String fileName = ofd.FileName;
                var rawdatas = OpenResultCSVFile(fileName);

                ReadInData = ParseSurfaceRawData(rawdatas, 100, 100);
                           

                double zMin = ReadInData.Min;
                double zMax = ReadInData.Max;

                int n = 100;
                int m = 100;
                int width = 2;
                int height = 2;
                int top = 0;

                for (int x = 0; x < n; x++)
                {
                    int left = 0;
                    for (int y = 0; y < m; y++)
                    {
                        //double xi = 2*x - 100;
                        //double yi = 2*y - 100;

                        //if (xi * xi + yi * yi > 100 * 100)
                        //{
                        //    continue;
                        //}
                        double ptelement = ReadInData.RawData[x][y];
                        double z = ((ptelement - zMin) / (zMax - zMin));

                        if (z < 0.0) z = 0.0;
                        if (z > 1) z = 1;


                        int indexColor = (int)Math.Floor((colors.Length - 1) * z);
                        Color clr = HexToColor(colors[indexColor]);
                        SolidColorBrush solidColorBrush = new SolidColorBrush(clr);

                        // Create the rectangle
                        Rectangle rec = new Rectangle()
                        {
                            Width = width,
                            Height = height,
                            Fill = solidColorBrush
                            //Fill = Brushes.Green
                        };

                        // Add to a canvas for example
                        canDrawing.Children.Add(rec);
                        Canvas.SetTop(rec, top);
                        Canvas.SetLeft(rec, left);
                        left += width;
                    }
                    top += height;
                }
            }
        }


        private void MainWindow_Resize(object sender, RoutedEventArgs e)
        {
            //this.Left = 0;
            //this.Top = 0;
            //this.Width = System.Windows.SystemParameters.PrimaryScreenWidth;
            //this.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
            this.cWidth = this.canDrawing.ActualWidth;
            this.cHeight = this.canDrawing.ActualHeight;
            this.canvasWidthInfo.Text = this.cWidth.ToString();
            this.canvasHeightInfo.Text = this.cHeight.ToString();

            double height = canDrawing.ActualHeight;
            double width = canDrawing.ActualWidth;
            //double zoom = e.Delta;
            height += 2;
            width += 2;
            ScaleTransform sc = new ScaleTransform(width, height);
            canDrawing.LayoutTransform = sc;
            canDrawing.UpdateLayout();

            //this.canDrawing.Clip = new EllipseGeometry(new Point(100, 100), 100, 100);
            //ScaleTransform st = new ScaleTransform(this.Width / 1366, this.Height / 768,0,0);
            //canDrawing.RenderTransform = st;
        }
        public double[,] OpenResultCSVFile(string filePath)
        {

            double[,] ret = new double[101, 101];
            //double[][] rets = new double[101][];

            Encoding encoding = Encoding.ASCII;//

            FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);

            //StreamReader sr = new StreamReader(fs, Encoding.UTF8);
            StreamReader sr = new StreamReader(fs, encoding);
            //string fileContent = sr.ReadToEnd();
            //encoding = sr.CurrentEncoding;
            //记录每次读取的一行记录
            string strLine = "";
            //记录每行记录中的各字段内容
            string[] aryLine = null;
            string[] tableHead = null;
            //标示列数
            int columnCount = 0;
            //标示是否是读取的第一行
            bool IsFirst = true;
            //逐行读取CSV中的数据


            double max = -100000;
            double min = 100000;

            Dictionary<string, int> elementCount = new Dictionary<string, int>();

            SortedDictionary<int, int> ValueCount = new SortedDictionary<int, int>();



            int xIndex = 0;
            while ((strLine = sr.ReadLine()) != null)
            {
                aryLine = strLine.Split(',');

                //rets[xIndex] = new double[101];

                for (int yIndex = 0; yIndex < 101; yIndex++)
                {
                    if (String.IsNullOrEmpty(aryLine[yIndex]))
                        break;

                    double zValueIn = double.Parse(aryLine[yIndex]);


                    ret[xIndex, yIndex] = zValueIn;
                }

                xIndex++;
                if (xIndex == 101)
                    break;
            }
            sr.Close();
            fs.Close();

            return ret;
        }

        public ReadInTemp ParseSurfaceRawData(double[,] rawdata, int width, int height)
        {
            double[][] rets = new double[height][];


            double max = -100000;
            double min = 100000;

            Dictionary<string, int> elementCount = new Dictionary<string, int>();

            SortedDictionary<int, int> ValueCount = new SortedDictionary<int, int>();

            double[] arrayRawDatas = new double[width * height];
            int arrayIndex = 0;

            int xIndex = 0;
            for (int row = 0; row < height; row++)
            {


                rets[xIndex] = new double[width];

                for (int yIndex = 0; yIndex < width; yIndex++)
                {
                    double zValueIn = rawdata[row, yIndex];

                    arrayRawDatas[arrayIndex++] = zValueIn;

                    //注意平均值
                    // int zValue =  (int)((zValueIn - AverageValue) * 1000);

                    int zValue = (int)((zValueIn) * 100000);

                    rets[xIndex][yIndex] = zValue;

                    if (ValueCount.ContainsKey(zValue))
                    {
                        ValueCount[zValue]++;
                    }
                    else
                    {
                        ValueCount.Add(zValue, 1);
                    }

                    String key = zValue.ToString("f2");

                    if (elementCount.ContainsKey(key))
                    {
                        elementCount[key]++;
                    }
                    else
                    {
                        elementCount.Add(key, 1);
                    }

                    if (zValue > max)
                    {
                        max = zValue;
                    }

                    if (zValue < min)
                    {
                        min = zValue;
                    }
                }

                xIndex++;

            }

            string whoIsMax = "0";
            int whoIsMaxValue = -10000;

            foreach (var item in elementCount)
            {
                if (item.Value > whoIsMaxValue)
                {
                    whoIsMax = item.Key;
                }
            }

            ReadInTemp retTemp = new ReadInTemp();
            retTemp.RawData = rets;
            retTemp.RawDataArray = arrayRawDatas;
            retTemp.Max = max;
            retTemp.Min = min;
            retTemp.Mid = double.Parse(whoIsMax);

            retTemp.W = width;
            retTemp.H = height;

            retTemp.ValueCount = ValueCount;

            return retTemp;
        }

        public static Color HexToColor(string hex)
        {
            byte br = byte.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
            byte bg = byte.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.HexNumber);
            byte bb = byte.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.HexNumber);
            //byte cc = byte.Parse(hex.Substring(6, 2), System.Globalization.NumberStyles.HexNumber);
            int r = br;
            int g = bg;
            int b = bb;
            //int a = cc / 255;
            return Color.FromRgb(br, bg, bb);
        }
    }
}
